package com.lantzuc.lanucbackend.filter;

import com.lantzuc.lanucbackend.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = ("/user"))
public class JwtAuthenticationFilter implements Filter {

    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    
    // 排除认证的路径
    private static final String[] EXCLUDE_PATHS = {
        "/user/login",
        "/user/register",
        "/doc.html",
        "/webjars/",
        "/swagger-resources",
        "/v2/api-docs"
    };
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("JWT认证过滤器初始化完成");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                        FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 设置响应头
        setupResponseHeaders(httpResponse);
        
        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        
        // 获取请求路径
        String requestPath = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String path = requestPath.substring(contextPath.length());
        
        // 检查是否为排除路径
        if (isExcludePath(path)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 获取认证头部
        String authHeader = httpRequest.getHeader(AUTH_HEADER);
        
        // 检查认证头是否存在且格式正确
        if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
            sendUnauthorizedResponse(httpResponse, "请先登录");
            return;
        }
        
        // 提取 JWT 令牌
        String jwtToken = authHeader.substring(BEARER_PREFIX.length()).trim();
        
        try {
            // 验证 JWT 令牌
            if (!JwtUtils.validateToken(jwtToken)) {
                sendUnauthorizedResponse(httpResponse, "令牌无效或已过期");
                return;
            }
            
            // 从 JWT 中解析用户信息
            Long userId = JwtUtils.getUserIdFromToken(jwtToken);
            String userAccount = JwtUtils.getUserAccountFromToken(jwtToken);
            String userName = JwtUtils.getUserNameFromToken(jwtToken);
            
            // 将用户信息放入请求属性，供后续使用
            httpRequest.setAttribute("id", userId);
            httpRequest.setAttribute("userAccount", userAccount);
            httpRequest.setAttribute("userName", userName);
            
            System.out.println("JWT认证成功 - 用户ID: " + userId + ", 账号: " + userAccount);
            
            // 继续过滤器链
            chain.doFilter(request, response);
            
        } catch (Exception e) {
            sendUnauthorizedResponse(httpResponse, "令牌解析失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查是否为排除路径（不需要认证的路径）
     */
    private boolean isExcludePath(String path) {
        for (String excludePath : EXCLUDE_PATHS) {
            if (path.startsWith(excludePath)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 设置响应头
     */
    private void setupResponseHeaders(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
    }
    
    /**
     * 发送未认证错误响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        String jsonResponse = String.format(
            "{\"code\": 401, \"message\": \"%s\", \"data\": null, \"description\": \"未授权访问\"}",
            message
        );
        response.getWriter().write(jsonResponse);
    }
    
    @Override
    public void destroy() {
        System.out.println("JWT认证过滤器被销毁");
    }
}